package com.itheima.reggie.controller;

import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired(required = false)
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee){
        R<Employee> result = employeeService.login(employee);
        //判断是否登录成功，成功就把用户名存入session

        if (result.getCode() == 1) {
            session.setAttribute("employee",result.getData().getId());
        }
        return result;
    }

    @PostMapping("/logout")
    public R<String> logout(){
        session.invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee){
        Long empId = (Long) session.getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("success");
    }

    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  String name){

        return employeeService.findByPage(page,pageSize,name);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee){
        Long empId = (Long) session.getAttribute("employee");
        employee.setUpdateUser(empId);

        employeeService.update(employee);
        return R.success("success");
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable("id") Long id){
        return employeeService.findById(id);
    }
}
